// src/examples/ChatStateManagementExample.js
// 聊天状态管理使用示例

// 1. 在组件中获取当前聊天信息
export const getCurrentChatExample = {
  computed: {
    currentChat() {
      return this.$store.getters.currentChat;
    },
    
    currentChatId() {
      return this.$store.getters.currentChatId;
    },
    
    currentMessages() {
      return this.$store.getters.currentMessages;
    },
    
    isOnline() {
      return this.$store.getters.isOnline;
    },
    
    isSending() {
      return this.$store.getters.isSending;
    }
  }
};

// 2. 在组件中设置当前聊天
export const setCurrentChatExample = {
  methods: {
    selectChat(chatInfo) {
      // 设置当前聊天
      this.$store.dispatch('chat/setCurrentChat', chatInfo);
      
      // 加载聊天消息
      this.$store.dispatch('chat/loadChatMessages', {
        chatId: chatInfo.friendshipId,
        chatType: chatInfo.type === 1 ? 'single' : 'group'
      });
    }
  }
};

// 3. 在组件中发送消息
export const sendMessageExample = {
  methods: {
    async sendMessage(messageData) {
      try {
        await this.$store.dispatch('chat/sendMessage', {
          content: messageData.content,
          extend: messageData.extend || 0,
          chatType: this.chatType,
          quoteId: messageData.quoteId,
          atUserIds: messageData.atUserIds || []
        });
      } catch (error) {
        console.error('发送消息失败:', error);
      }
    }
  }
};

// 4. 在组件中监听消息接收
export const receiveMessageExample = {
  mounted() {
    // 监听WebSocket消息
    window.addEventListener('receiverMessage', this.handleMessageReceive);
  },
  
  methods: {
    handleMessageReceive(event) {
      const message = event.detail.data.message;
      
      // 使用状态管理接收消息
      this.$store.dispatch('chat/receiveMessage', message);
    }
  },
  
  beforeDestroy() {
    window.removeEventListener('receiverMessage', this.handleMessageReceive);
  }
};

// 5. 在组件中获取未读消息数量
export const unreadCountExample = {
  computed: {
    unreadCount() {
      return this.$store.getters['chat/unreadCount'](this.chatId);
    },
    
    totalUnreadCount() {
      return this.$store.getters.totalUnreadCount;
    }
  }
};

// 6. 在组件中标记消息已读
export const markAsReadExample = {
  methods: {
    markMessagesAsRead(chatId) {
      this.$store.dispatch('chat/markMessagesAsRead', chatId);
    }
  }
};

// 7. 使用事件总线进行组件间通信
import eventBus, { CHAT_EVENTS } from '@/utils/eventBus';

export const eventBusExample = {
  methods: {
    // 发送聊天切换事件
    switchChat(chatInfo) {
      eventBus.emit(CHAT_EVENTS.CHAT_SWITCH, chatInfo);
    },
    
    // 发送消息发送事件
    sendMessageEvent(messageData) {
      eventBus.emit(CHAT_EVENTS.MESSAGE_SEND, messageData);
    }
  },
  
  mounted() {
    // 监听聊天切换事件
    eventBus.on(CHAT_EVENTS.CHAT_SWITCH, this.handleChatSwitch);
    
    // 监听消息发送事件
    eventBus.on(CHAT_EVENTS.MESSAGE_SEND, this.handleMessageSend);
  },
  
  beforeDestroy() {
    eventBus.off(CHAT_EVENTS.CHAT_SWITCH, this.handleChatSwitch);
    eventBus.off(CHAT_EVENTS.MESSAGE_SEND, this.handleMessageSend);
  }
};
